$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
    /* 0516 正式未添加的功能扩展
        getLcbjhHkTotalAmt
        getXshtInPay
        getProjectSybyTotalAmt
        getFbyfdTotalAmtByPhidPc
        getSjcztbTotalAmt
     */
    const mstform = $NG.getCmpApi("p_form_servicee_qs_m")
    const dgrid = $NG.getCmpApi("p_form_servicee_qs_d")

    // init
    switch (page.oType) {
        case "edit":
        case "add":
            cntMFilter()
            getPtInfoByPhid()
            getCntMInfoByPhid()
            getLcbjhHkTotalAmt()
            getXshtInPay()
            getFbyfdTotalAmtByPhidPc()
            getSjcztbTotalAmt()
            // cnt
            getProjectSybyTotalAmt()
            GetIncomeCostData()
            break
        case "view":

    }
    // 表头监听器
    // 防止各种表头赋值无法控制异步同步导致不顺序执行取数错误情况
    const headValueEvent = (() => {
        const obj = {};
        const fields = [
            'u_htxe', 'u_yhje', 'u_yhkje', 'u_yhwhje', 'u_cgyfje', 'u_fbyfje', 'u_czby',
            'u_dqwcl', 'u_srqrje', 'u_srce', 'u_ywghs', 'u_ywgmll', 'u_mllzj',
            'u_zjl', 'u_ycztwg', 'u_ycztwgmll', 'u_ychtezj', 'u_ychtwcl', 'u_yjzjl'
        ];
        // getAll 方法
        Object.defineProperty(obj, 'getAll', {
            value: function () {
                let map = {}
                for (let key of fields) {
                    map[key] = this['_' + key]
                }
                return map
            },
            writable: true,
            enumerable: false,
            configurable: false
        });
        // sumAmt 方法
        Object.defineProperty(obj, 'sumAmt', {
            value: function () {
                this._u_yhwhje = this._u_yhje - this._u_yhkje // 应未回款金额
                this._u_srce = this._u_yhkje - this._u_srqrje // 收入差额
                this._u_dqwcl = this.u_srqrje ? this.u_srqrje / this._u_htxe : 0
                const _map = this.getAll()
                $NG.updateState((updater) => {
                    updater.data.p_form_servicee_qs_m.setProps({ ..._map })
                })
            },
            writable: true,
            enumerable: false,
            configurable: false
        });


        for (const field of fields) {
            const privateKey = `_${field}`;

            Object.defineProperty(obj, privateKey, {
                value: 0,
                writable: true,
                enumerable: false,
                configurable: false
            });
            Object.defineProperty(obj, field, {
                enumerable: true,
                configurable: false,
                get() {
                    return obj[privateKey];
                },
                set(val) {
                    obj[privateKey] = (Number(val) || 0);
                    obj.sumAmt();
                }
            });
        }

        return obj;
    })();

    // 入口
    function cntMain() {
        getProjectSybyTotalAmt()
        GetIncomeCostData()
    }

    function phidPcMain() {
        cntMFilter()
        getPtInfoByPhid()
        getCntMInfoByPhid()
        getLcbjhHkTotalAmt()
        getXshtInPay()
        getFbyfdTotalAmtByPhidPc()
        getSjcztbTotalAmt()
        GetIncomeCostData()
    }

    useValuesChange(({ args }) => {
        phidPcMain()
    }, "p_form_servicee_qs_m.phid_pc")

    useValuesChange(({ args }) => {
        cntMain()
    }, "p_form_servicee_qs_m.u_cnt_name")

    useUpdateRows(({ args }) => {
        sumAmt(args[0])
    }, "p_form_servicee_qs_d")

    // 合同过滤
    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_servicee_qs_m.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = mstform.getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!mstform.getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        phid_pc: mstform.getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }

    // 获取项目信息
    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                $NG.updateState((updater) => {
                    updater.data.p_form_servicee_qs_m.setProps({
                        //项目编码
                        u_pc_no: datas.pc_no,
                        //项目金额
                        approx_contract_fc: datas.approx_contract_fc,
                        //计划开工日期
                        start_date: datas.start_date,
                        //计划完工日期
                        end_date: datas.end_date,
                        u_gcgk: datas.descript,
                        //售前顾问
                        u_sqgw: {
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //项目经理
                        phid_emp: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        //组织
                        phid_org: {
                            value: datas.phid_org_phid,
                            label: datas.phid_org_name,
                        },
                        //区域中心
                        u_regional_center: {
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        //产品线
                        u_product_line: {
                            value: datas.midwife_phid,
                            label: datas.midwife_name,
                        },
                        //客户名称
                        customer: {
                            value: datas.customer_id,
                            label: datas.customer_name,
                        },
                        //部门
                        u_dept: {
                            value: datas.dept_phid,
                            label: datas.dept_name,
                        },
                        //项目类型
                        u_pc_type: {
                            value: datas.type_phid,
                            label: datas.type_name,
                        },
                        //项目预算组织编码
                        budget_org_code: datas.budget_org_no,
                        //项目预算组织
                        budget_org_phid: {
                            value: datas.budget_org_phid,
                            label: datas.budget_org_name,
                        },
                    });
                });
            });
        }
    }

    // 获取合同信息
    function getCntMInfoByPhid(params) {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_name").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // console.log(datas);

            headValueEvent.u_htxe = datas.cnt_sum_vat_fc

            $NG.updateState((updater) => {
                updater.data.p_form_servicee_qs_m.setProps({
                    u_cnt_no: datas.pcm_no, //合同编号
                    start_dt: datas.start_dt, //约定开工时间
                    end_dt: datas.end_dt, //约定完工时间
                    u_qdmll: datas.user_qdmllb,// 签单毛利
                    u_cshte: datas.init_cnt_amt,// 初始合同额
                    u_total_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同金额
                    u_htxe: datas.cnt_sum_vat_fc, //合同现额（未税）
                    //产品线
                    user_product_line: {
                        value: datas.midwife_phid,
                        label: datas.midwife_name,
                    },
                    //合同类型
                    u_cnt_type: {
                        value: datas.pct_id,
                        label: datas.pct_name,
                    },
                    //甲方单位
                    u_customer: {
                        value: datas.customer_id,
                        label: datas.customer_name,
                    },
                    //乙方单位
                    supply: {
                        value: datas.supply_id,
                        label: datas.supply_name,
                    },
                    //发票类型
                    u_invoice_type: {
                        value: datas.invoice_type_phid,
                        label: datas.invoice_type_name,
                    },
                    //购方信息（客户信息）（收票单位信息）
                    //单位名称
                    tick_id: {
                        value: datas.tick_id,
                        label: datas.tick_name,
                    },
                    //单位编码
                    tick_no: datas.tick_no,
                    //社会信用代码
                    tick_unisocialcredit: datas.tick_unisocialcredit,
                    //单位地址
                    tick_taxaddress: datas.tick_taxaddress,
                    //联系电话
                    tick_taxtelephone: datas.tick_taxtelephone,
                    //银行名称
                    tick_taxbankid: {
                        value: datas.tick_taxbankid,
                        label: datas.tick_taxbankname,
                    },
                    //银行账号
                    tick_taxaccountno: datas.tick_taxaccountno,
                    //销方信息（供应商信息）（开票单位信息）
                    //单位名称
                    inv_id: { value: datas.inv_id, label: datas.inv_name },
                    //单位编码
                    inv_no: datas.inv_no,
                    //社会信用代码
                    inv_unisocialcredit: datas.inv_unisocialcredit,
                    //单位地址
                    inv_taxaddress: datas.inv_taxaddress,
                    //联系电话
                    inv_taxtelephone: datas.inv_taxtelephone,
                    //银行名称
                    inv_taxbankid: {
                        value: datas.inv_taxbankid,
                        label: datas.inv_taxbankname,
                    },
                    //银行账号
                    inv_taxaccountno: datas.inv_taxaccountno,
                });
            });
        });
    }

    function sumAmt(rows, add = false) {
        const syms = ['+', '-', '/', '*']
        // 需要计算的所有key
        const itemKeys = ['u_csys', 'u_bg', 'u_dqys', 'u_sjys', 'u_zmje', 'u_cq', 'u_zh', 'u_sjfs', 'u_jcb', 'u_cy', 'u_hxdfs', 'u_ztsj', 'u_yscy'];
        // 汇总行架构填写（自定义）(我未暂适配)括号优先级
        const sumMap = {
            '项目毛利': {
                exclude: [], // 排除列表（排除不计算的key）
                val: '收入 - 直接成本',  // 计算逻辑
            },
            '毛利率%': {
                exclude: [],
                val: '项目毛利 / 收入'
            }
        }
        rows.forEach(item => {
            item.u_cq = (Number(item.u_sjfs) || 0) - (Number(item.u_zmje) || 0)
            item.u_zh = Math.abs((Number(item.u_sjfs) || 0) - (Number(item.u_zmje) || 0))
            item.u_cy = (Number(item.u_sjys) || 0) - (Number(item.u_sjfs) || 0)
            item.u_ztsj = (Number(item.u_hxdfs) || 0) + (Number(item.u_sjfs) || 0)
            item.u_yscy = (Number(item.u_dqys) || 0) - (Number(item.u_ztsj) || 0)
        })
        rows.forEach(item => {
            const keys = Object.keys(sumMap)
            // 找需要计算的行
            if (keys.includes(item.u_qdxm)) {
                const val = sumMap[item.u_qdxm].val.replaceAll(' ', "")
                const exclude = sumMap[item.u_qdxm].exclude
                let init = 0
                let ind = 0
                let tempKey = ''
                let sys = ''
                for (const ve of val) {
                    ind++
                    (val.length == ind) && (tempKey += ve)
                    if (syms.includes(ve) || ind == val.length) {
                        // 查找相应数据
                        let it = rows.filter(ite => ite.u_qdxm == tempKey)
                        if (it.length == 0) {
                            throw (`填写sumMap计算有问题,${tempKey} 未找到！`)
                        } else if (it.length != 1) {
                            throw (`填写sumMap计算有问题,${tempKey} 发现多个！`)
                        }
                        it = it[0]
                        if (init == 0) {
                            itemKeys.forEach(el => {
                                if (!exclude.includes(el)) {
                                    item[el] = (Number(it[el]) || 0)
                                }
                            })
                        } else {
                            switch (sys) {
                                case '+':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number(item[el]) || 0) + (Number(it[el]) || 0)
                                        }
                                    })
                                    break;
                                case '-':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number(item[el]) || 0) - (Number(it[el]) || 0)
                                        }
                                    })
                                    break;
                                case '/':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number((Number(item[el]) || 0) / (Number(it[el]) || 0)) || 0)
                                        }
                                    })
                                    break;
                                case '*':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number((Number(item[el]) || 0) * (Number(it[el]) || 0)) || 0)
                                        }
                                    })
                                    break;
                            }
                        }
                        tempKey = ''
                        init++
                        sys = ve
                    } else {
                        tempKey += ve
                    }
                }
            }
        })

        if (add) {
            dgrid.clearRows().then(() => {
                dgrid.addRows([...rows])
            })
        } else {
            dgrid.refreshView()
        }
    }

    // 获取里程碑计划回款明细的应回款金额
    function getLcbjhHkTotalAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getLcbjhHkTotalAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            window._catch_lcb_hk_totalAmt = _data.yhk_total_amt
            // 赋值应汇款金额
            page.oType == "add" && (headValueEvent.u_yhje = _data.yhk_total_amt)
        })

    }

    // 获取销售合同收款汇总值
    function getXshtInPay() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getXshtInPay", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            headValueEvent.u_yhkje = _data.total_amt
        })
    }

    // 获取项目收入报验相关金额
    function getProjectSybyTotalAmt() {
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if (!cnt) return
        $NG.execServer("getProjectSybyTotalAmt", { cnt }, (res) => {
            const _data = JSON.parse(res.data)[0].extendObjects
            headValueEvent.u_srqrje = _data.total_amt
        })
    }

    // 分包应付单本期应付金额
    function getFbyfdTotalAmtByPhidPc() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getFbyfdTotalAmtByPhidPc", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            headValueEvent.u_fbyfje = _data.bcsq_total_amt
        })
    }

    // 获取实际产值填报
    function getSjcztbTotalAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getSjcztbTotalAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            headValueEvent.u_czby = _data.total_amt
        })
    }

    // 成本核算分析
    function GetIncomeCostData() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        const cnt = mstform.getItem("u_cnt_name").getValue()
        console.log(`获取核算信息`, phid_pc, cnt);
        if (!cnt || !phid_pc) return
        $NG.execServer("GetIncomeCostData", { pc: phid_pc, cnt: cnt }, (res) => {
            if (res.count == 0) return
            const data = JSON.parse(res.data).reduce((value, items) => {
                const item = items.extendObjects
                const map = {
                    u_qdxm: item.qdxm,
                    u_csys: item.csys,
                    u_bg: item.bg,
                    u_dqys: item.dqys,
                    u_sjys: item.sjys,
                    u_zmje: item.zmje,
                    u_sjfs: item.sjfs,
                    u_jcb: item.jcb,
                }
                value.push(map)
                return value
            }, [])
            sumAmt(data, true)
        })
    }
})